import 'package:flutter/cupertino.dart';
import 'package:intl/intl.dart';

extension NumExtentions on num {
  ///把数字格式化为人民币（带分隔符）
  String rmb({String prefix = ""}) {
    return NumberFormat.currency(
      symbol: "",
      decimalDigits: 2,
      customPattern: "$prefix##,##0.0#",
    ).format(this);
  }

  String rmbWithPrefixUnit(String unit, {String prefix = "￥", int num = 2}) {
    return "$prefix${this.toStringAsFixed(num)}${unit.isNotEmpty == true ? "/" + unit : ""}";
  }

  String asDistance() {
    if (this < 1.0) return "${(this * 1000).round()} M";
    if (this < 10.0) return "${this.toStringAsFixed(1)} KM";
    return "${this.round()} KM";
  }

  String asDistance2([String space = ""]) {
    if (this < 1000) return "${this.round()}${space}m";
    if (this < 10.0 * 1000)
      return "${(this / 1000.0).toStringAsFixed(2)}${space}KM";
    return "${(this / 1000).round()}${space}KM";
  }

  DateTime toDateTime() {
    return DateTime.fromMillisecondsSinceEpoch(this as int);
  }

  String memorySize() {
    if (this < 1024) return "${this}B";
    if (this < 1024 * 1024)
      return "${(this * 1.0 / 1024).toStringAsFixed(2)}KB";
    if (this < 1024 * 1024 * 1024)
      return "${(this * 1.0 / 1024 / 1024).toStringAsFixed(2)}MB";

    return "${(this * 1.0 / 1024 / 1024 / 1024).toStringAsFixed(2)}GB";
  }

  double asChildAspectRatio(
    BuildContext context,
    int crossAxisCount,
    double crossAxisSpacing,
    double horizontalPadding,
  ) {
    final screenWidth = MediaQuery.of(context).size.width;
    final widgetWidth = screenWidth -
        horizontalPadding * 2 -
        crossAxisSpacing * (crossAxisCount - 1);
    return widgetWidth / crossAxisCount / this;
  }

  int beforeDot() {
    return toInt();
  }

  String afterDot([int width = 2]) {
    final tmp = (this - toInt()).toStringAsFixed(width);
    return tmp.substring(tmp.indexOf("."));
  }

  ///find the closest value to target in values
  ///e.g target 2.3, values = [1.0, 1.5, 2.0, 2.5, 3.0]. it should return 2.5
  num? findClosestValue(List<num> values) {
    if (values.isEmpty) return null;
    if (values.length == 1) return values.first;

    var closestValue;
    var minDistance = double.infinity;
    for (double v in values as Iterable<double>) {
      final num distance = (this - v).abs();
      if (distance < minDistance) {
        minDistance = distance as double;
        closestValue = v;
      }
    }
    return closestValue;
  }
}
